#include "lauxlib.h"
#include "lua.h"
#include "lua_editor_extension.hpp"
#include "lua_function_extension.hpp"
#include "scripting/scripting_module.h"
#include "utils/log.hpp"
#include "lua_base.hpp"


bool ModuleInit()
{
    L_INFO("Pluto Scripting Module Init...");

    auto state = LuaShared::NewState();

    // Our Lua code, it simply prints a Hello, World message
    const char * code = "log_d('Hello World from lua script')";

    // Here we load the string and use lua_pcall for run the code
    if (luaL_loadstring(state, code) == LUA_OK) {
        if (lua_pcall(state, 0, 0, 0) == LUA_OK) {
            // If it was executed successfuly we
            // remove the code from the stack
            lua_pop(state, lua_gettop(state));
        }
    }

    LuaShared::CloseState(state);

    return true;
}

void ModuleCleanup()
{
    L_INFO("Pluto Scripting Module Cleanup...");
}

IScript* BuildScript(const ScriptBuildInfo *info)
{
    RC_ERROR(nullptr, !(info && info->Valid()), "Invalid Script Build Info Passed!!!");
    if (strcmp(info->usage, "editor") == 0) {
        return LuaEditorExtension::create(EditorTargetFromString(info->usage_extra), info->title, info->code, info->file_path);
    } else if (strcmp(info->usage, "function") == 0) {
        return LuaFunctionExtension::create(info->title, info->code, info->file_path);
    }
    return nullptr;
}
